package com.liruo.treasureattic.service.url.schedule;

import com.liruo.treasureattic.common.model.constant.RedisConstant;
import com.liruo.treasureattic.common.model.other.Pair;
import com.liruo.treasureattic.service.url.service.UrlFolderService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author:liruo
 * @Date:2022-11-29-16:51:55
 * @Desc
 */
@Component
@Slf4j
public class UrlFolderRealDeleteJob {
    @Resource
    private UrlFolderService urlFolderService;
    @Resource
    private RedissonClient redissonClient;


    //暂时就不修改了，默认可以在回收站保存7天
    private int delValCycleDays = 7;

    /**
     * 因为可能是分布式的 ，所以加锁，同一时间只执行一次
     * cron = 每个星期一的早上1点30分0秒
     *
     * realDeleteUrlFolder和realDeleteUrl只需要删除过期的就行
     *   folder的子folder和url几乎是同一时间没的，所以不用管
     */
    @Scheduled(cron = "0 30 1 * * 1")
    public void doRealDeleteUrlFolder(){
        RLock lock = redissonClient.getLock(RedisConstant.TREASURE_URL_LOCK_SCHEDULE_DELETE);
        try {
            //最多1天执行完
            if(lock.tryLock(-1,1, TimeUnit.DAYS)){
                //mybatis 不能真地删除，只能手写sql
                Pair<Integer, Integer> pair = urlFolderService.realDeleteUrlFolder(delValCycleDays);
                log.debug("每个星期一的早上1点30分0秒, every machine use redis to fight for lock to single to real delete folders[{}] and urls[{}]",
                        pair.getKey(), pair.getValue()
                );
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }
}
